import cloud from "d3-cloud";

export function generateWordCloud(container, words) {
    if (!container) return;

    const width = container.clientWidth;
    const height = container.clientHeight;
    d3.select(container).selectAll("*").remove();

    const svg = d3.select(container).append("svg").attr("width", width).attr("height", height);
    const group = svg.append("g").attr("transform", `translate(${width / 2},${height / 2})`);
    const color = d3.scaleOrdinal(d3.schemeCategory10);

    // 使用d3-cloud布局词云
    const layout = cloud()
        .size([width, height])
        .words(words.map((d) => ({text: d.text, size: d.size})))
        .padding(5)
        .rotate(() => (Math.random() > 0.5 ? 0 : 90))
        .font("Impact")
        .fontSize((d) => d.size)
        .on("end", draw);

    layout.start();

    function draw(words) {
        group
            .selectAll("text")
            .data(words)
            .enter()
            .append("text")
            .style("font-size", (d) => `${d.size}px`)
            .style("font-family", "Impact")
            .style("fill", (d, i) => color(i))
            .attr("text-anchor", "middle")
            .attr("transform", (d) => `translate(${d.x}, ${d.y})rotate(${d.rotate})`)
            .text((d) => d.text);
    }
}